package dk.lector;

import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import dk.lector.datasource.DocDBRepository;
import dk.lector.domain.TeamShareMobile;
import dk.lector.domain.entities.Document;
import dk.lector.providers.CACHEDDOC_VIEWContentProvider;
import dk.lector.providers.DOC_METADATAContentProvider;
import dk.lector.providers.DOC_STOREDContentProvider;
import dk.lector.remote.TSMobileService;
import dk.lector.service.DocumentService;
import dk.lector.utils.TSProgressDialog;

public class DocumentLoaderActivity extends Activity {
	private String TAG = this.getClass().getSimpleName();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Log.d(TAG, "onCreate()");
		int documentID = getIntent().getIntExtra(
				DOC_METADATAContentProvider._ID, 0);
		if (documentID == 0) {
			Log.d(TAG, "No documentID set in Intent");
			finish();
			return;
		}

		try {
			Document documentDTO = new getDocumentDTOByID().execute(documentID)
					.get();

			setContentView(R.layout.documentinfo_layout);
			checkButtons(documentDTO);
			setTextView(documentDTO);

		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void checkButtons(final Document documentDTO) {

		((Button) findViewById(R.id.btn_docinfo_cancel))
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						// TODO Auto-generated method stub
						DocumentLoaderActivity.this.finish();
					}
				});
		if (documentDTO.getSerVersion() != documentDTO.getCurVersion()) {
			((Button) findViewById(R.id.btn_docinfo_download))
					.setOnClickListener(new OnClickListener() {

						public void onClick(View v) {
							// TODO Auto-generated method stub
							new iniateDownloadDocumentByID()
									.execute(documentDTO);
							DocumentLoaderActivity.this.finish();
						}
					});
		} else {
			((Button) findViewById(R.id.btn_docinfo_download))
					.setVisibility(View.GONE);
		}
		// if (documentDTO.getCurVersion() == documentDTO.getSerVersion() &&
		// documentDTO.getFile_size() != 0 && documentDTO.getFile_size() ==
		// documentDTO.getFile_size_persistet())
		if (documentDTO.getCurVersion() > 0.0) {
			((Button) findViewById(R.id.btn_docinfo_view))
					.setOnClickListener(new OnClickListener() {

						public void onClick(View v) {
							// TODO Auto-generated method stub
							openFile(
									Uri.parse("file://"
											+ documentDTO.getFile_path()),
									documentDTO.getFile_extension());
							DocumentLoaderActivity.this.finish();
						}
					});

		} else {
			((Button) findViewById(R.id.btn_docinfo_view))
					.setVisibility(View.GONE);
		}

	}

	private void setTextView(Document documentDTO) {

		((TextView) findViewById(R.id.docid_textview)).setText("ID: "
				+ documentDTO.getId());
		((TextView) findViewById(R.id.doctitle_textview)).setText("Title: "
				+ documentDTO.getTitel());
		((TextView) findViewById(R.id.docserverversion_textview))
				.setText("Server Version: " + documentDTO.getSerVersion());

		if (documentDTO.getCurVersion() != 0.0) {
			((TextView) findViewById(R.id.doccurrentversion_textview))
					.setText("Current Version: " + documentDTO.getCurVersion());

		} else {
			((TextView) findViewById(R.id.doccurrentversion_textview))
					.setVisibility(View.GONE);
		}

	}

	private class iniateDownloadDocumentByID extends
			AsyncTask<Document, Void, Void> {

		@Override
		protected Void doInBackground(Document... documentDTO) {
			// TODO Auto-generated method stub

			ContentValues docmetavalues = new ContentValues();
			docmetavalues.put(DOC_METADATAContentProvider._ID,
					documentDTO[0].getId());
			docmetavalues.put(DOC_METADATAContentProvider.NAME,
					documentDTO[0].getName());
			docmetavalues.put(DOC_METADATAContentProvider.TITLE,
					documentDTO[0].getName());
			docmetavalues.put(DOC_METADATAContentProvider.VERSION,
					documentDTO[0].getSerVersion());

			docmetavalues.put(DOC_METADATAContentProvider.ICON_ID,
					documentDTO[0].getIcon_id());
			docmetavalues.put(DOC_METADATAContentProvider.FILE_EXTENSION,
					documentDTO[0].getFile_extension());

			DocDBRepository.updateOrInsertDocMetaData(getBaseContext(),
					docmetavalues);

			ContentValues docstoredvalues = new ContentValues();
			docstoredvalues.put(DOC_STOREDContentProvider._ID,
					documentDTO[0].getId());
			docstoredvalues.put(DOC_STOREDContentProvider.TIMESTAMP,
					System.currentTimeMillis());
			docstoredvalues.put(DOC_STOREDContentProvider.TIMESTAMP_ACTIVITY,
					System.currentTimeMillis());
			docstoredvalues.put(DOC_STOREDContentProvider.FILE_PATH,
					Environment.getExternalStorageDirectory().getAbsolutePath()
							+ "/" + documentDTO[0].getName());
			docstoredvalues.put(DOC_STOREDContentProvider.FILE_SIZE, 0);
			docstoredvalues.put(DOC_STOREDContentProvider.FILE_SIZE_PERSISTET,
					0);

			DocDBRepository.updateOrInsertStoredDocData(getBaseContext(),
					docstoredvalues);

			Intent downloadServiceIntent = new Intent(
					DocumentLoaderActivity.this, DocumentService.class);
			downloadServiceIntent.putExtra(DOC_METADATAContentProvider._ID,
					documentDTO[0].getId());

		TeamShareMobile core = (TeamShareMobile) DocumentLoaderActivity.this.getApplication();
			
			String username = core.getUser().getUsername();
			String password = core.getUser().getPassword();
					
			downloadServiceIntent.putExtra("username", username);
			downloadServiceIntent.putExtra("password", password);

			getBaseContext().startService(downloadServiceIntent);

			return null;
		}

	}

	private class getDocumentDTOByID extends AsyncTask<Integer, Void, Document> {

		@Override
		protected void onPreExecute() {
			TSProgressDialog.showDialog(DocumentLoaderActivity.this,
					R.string.fetching_documentdata_text);
			super.onPreExecute();
		}

		@Override
		protected Document doInBackground(Integer... documentID) {
			
			TeamShareMobile core = (TeamShareMobile) DocumentLoaderActivity.this.getApplication();
			
			String username = core.getUser().getUsername();
			String password = core.getUser().getPassword();
					
			Document documentDTO = new Document();
			documentDTO = mapServerValuesToDTO(documentDTO,
					TSMobileService.getDocumentInfoByID(getBaseContext(),
							documentID[0], username, password));
			documentDTO = mapCachedCursorToDTO(documentDTO,
					DocDBRepository.getDocumentByID(getBaseContext(),
							documentID[0]));
			return documentDTO;

		}

		@Override
		protected void onPostExecute(Document result) {
			TSProgressDialog.dismissDialog();
			super.onPostExecute(result);
		}

		private Document mapServerValuesToDTO(Document documentDTO,
				ContentValues values) {
			documentDTO.setId(values
					.getAsInteger(DOC_METADATAContentProvider._ID));
			documentDTO.setName(values
					.getAsString(DOC_METADATAContentProvider.NAME));
			documentDTO.setTitel(values
					.getAsString(DOC_METADATAContentProvider.TITLE));
			documentDTO.setIcon_id(values
					.getAsInteger(DOC_METADATAContentProvider.ICON_ID));
			documentDTO.setFile_extension(values
					.getAsString(DOC_METADATAContentProvider.FILE_EXTENSION));
			documentDTO.setSerVersion(values
					.getAsDouble(DOC_METADATAContentProvider.VERSION));
			// TODO Auto-generated method stub
			return documentDTO;
		}

		private Document mapCachedCursorToDTO(Document documentDTO,
				Cursor cursor) {
			if (cursor == null || cursor.getCount() == 0) {
				return documentDTO;
			} else {
				cursor.moveToFirst();
				documentDTO
						.setCurVersion(cursor.getDouble(cursor
								.getColumnIndex(CACHEDDOC_VIEWContentProvider.VERSION)));
				documentDTO
						.setFile_path(cursor.getString(cursor
								.getColumnIndex(CACHEDDOC_VIEWContentProvider.FILE_PATH)));
				documentDTO
						.setFile_size(cursor.getInt(cursor
								.getColumnIndex(CACHEDDOC_VIEWContentProvider.FILE_SIZE)));
				documentDTO
						.setFile_size_persistet(cursor.getInt(cursor
								.getColumnIndex(CACHEDDOC_VIEWContentProvider.FILE_SIZE_PERSISTET)));
				return documentDTO;
			}

		}
	}

	public void openFile(Uri data, String fileextension) {
		Intent viewer = new Intent(Intent.ACTION_VIEW);
		viewer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

		MimeTypeMap mimes = MimeTypeMap.getSingleton();
		String mimetype = mimes.getMimeTypeFromExtension(fileextension);
		if (mimetype != null){
		Log.d(TAG, mimetype);
		}
		if (mimetype != null && hasViewerForMimeType(mimetype)) {
			viewer.setDataAndType(data, mimetype);
			startActivity(viewer);
		} else {
			Toast.makeText(this, R.string.no_viewer_text, Toast.LENGTH_LONG).show();
		}

	}
	public boolean hasViewerForMimeType(String mimetype) {
	    PackageManager packageManager = this.getPackageManager();
	    Intent testIntent = new Intent(Intent.ACTION_VIEW);
	    testIntent.setType(mimetype);
	    if (packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0) {
	    	Log.d(TAG, "hasViewerForMimeType returning true");
	    	return true;
	        
	    } else {
	    	Log.d(TAG, "hasViewerForMimeType returning false");
	        return false;
	    }
	}

}
